<?php
/*
 Если есть конструктор модуля, нужно обязятельно вызывать родлительский parent::__construct();
*/

/*
 * GRID example
 *
 * function sampleupdate(rowid, stringjson, gridId)
{
	var valString = stringjson.responseText;
	var rowdata = eval('(' + valString + ')' );
	jQuery(gridId).setRowData(rowid, rowdata );
	jQuery(gridId).editRow(rowid,true, function(id){},null, null, null, function(rowid, stringjson){sampleupdate(rowid, stringjson, gridId)});
	$(gridId + " input:checkbox'").unbind("click").bind("click", function(event){grideditrow($(this), gridId)} );
	$(gridId+" select").unbind("change").bind("change", function(event){grideditrow($(this), gridId)});
	blockGrid(gridId, 'hide');
}
 */


class RepairsModul extends BasicModulController implements BasicModulControllerInterface {

    // function __construct($registry = null){


    //

    //$this->modul_id = $this->getModulIdByIndex(MODUL_INDEX);

    /*if(isset($this->registry) AND ($this->registry->get('virtual_modul_index')) != '')
        $this->life_modul_index = $this->registry->get('virtual_modul_index');
    elseif(isset($this->registry) AND ($this->registry->get('modul_index')) != '')
        $this->life_modul_index = $this->registry->get('modul_index');
    */

    // $this->life_modul_index // 'about'
    //$this->modul_index = $this->registry->get('modul_index'); // 'Repairs'

    // [?] виджеты
    //$this->widget_enter_data = array();
    //$this->widget_enter_data['widget'] = array('1'=>'a'); //var_dump($this->widget_enter_data);

    // инициализация модели
    /*
    if( class_exists($this->modul_index, true) )
        $this->model = new $this->modul_index;
    else {        } */

    // инициализация представления
    /*$class_name = $this->modul_index . "View";

    $ModulView = new $class_name($this->modul_id); // [!] подставлять переменную с именем можудя
    $this->global_view = $ModulView->getView();    // глобальное представление
    $this->view = $ModulView; // представление модуля
    */
    // [test] установка переменных, полученных из модели
    // $this->view->Set('asd',1234);

    //self::$instance = $this;


    //  } // -- __construct

    /*
    function getHtml(){
        return $this->html;
    }

    // [!] сделать, чтобы рендерился шаблон модуля и шаблон отдельно главный
    // попробовать взять смарти из реестра или создать второй объект

    public static function getInstance($registry = null){
        // [!] метод обязателен для каждого модуля
        if (!isset(self::$instance)) {
            $className = __CLASS__;
            self::$instance = new $className($registry);
        }

        return self::$instance;
    } // --
    
    public static function getView(){
        $obj = static::getInstance();
        return $obj->view;
    }
    
    
    static function action(){
        //die(var_dump(__CLASS__));
        $obj = static::getInstance();

        $method = $obj->action;

        if( !method_exists($obj, $method) ) throw new Exception('No action exists');

        $obj->$method();

        //die(var_dump($obj->action));
    } // --
*/

    // -------- Repairs [origin] точка входа ----------
    function actionRepairsBasic(){

        $this->headCodeDynamic("console.log('actionRepairsBasic');");

        $this->html = $this->view->render();
        //$this->html = $this->view->fetch('basic.tpl');
    } // --


    // -------- Kitchen [virtual] точка входа ----------
    function actionKitchenBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        /*
        $photo_grid = new GridWrapper( $grid_name = "photo_kitchen");

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/kitchen/getphoto",
            'editurl' => PUBLIC_URL . "/kitchen/editCell",
            //'column_model' => $colModel,
            //'grid_config' => $grid_config,
        );

        $photo_grid->set($options);

        $photo_grid->populate();


        $this->view->grid_name = $grid_name;
        $this->view->photo_kitchen = $photo_grid->getHtml();
        */


        $this->html = $this->view->fetch('basic.tpl');
    } // --

    // -------- Hall [virtual] точка входа ----------
    function actionHallBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');

    }

    // -------- balkon [virtual] точка входа ----------
    function actionBalkonBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');
    }

    // -------- Room [virtual] точка входа ----------
    function actionRoomBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();



/* ///Old variant




        $photo_grid = new GridWrapper( $grid_unit );        // $photo_grid = new GridWrapper();

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/editCell",
            //'column_model' => $colModel,
            //'grid_config' => $grid_config,
        );

        $photo_grid->set($options);

        $photo_grid->populate();

        $this->view->grid_unit = $grid_unit;
        $this->view->photo_grid = $photo_grid->getHtml();
*/
        $path_of_script = PUBLIC_URL .'/js/jquery.fileupload.js';
        $path_to_load = PUBLIC_URL .'/js/jquery.fileupload.js';

        /*
        $asd = "
            function bindMultiload(e){
                        $('input[name=multiload]').fileupload({
                                url:'$path_to_load',
                                success:function(dat){
                                    if(dat.status == 'ok') { alert(dat.file); }
                                },
                                dataType:'json'
                            });
                    }


        ";
        */

        $multiload = "
            $.getScript('$path_of_script', function(){
                  //$( 'input[name=multiload]' ).off().on('mouseover', bindMultiload );
            });

        ";

        Controller::appendHeadCode($multiload);
       // Controller::appendHeadCodeDynamic($asd);

        $this->html = $this->view->fetch('basic.tpl');

    }

    /*
     * [универсальный] метод загрузки файлов с сервера на ftp
     */
    private function imageToFtp(array $photo_arr, $unit){



        $result = true;

        foreach($photo_arr as $k => $v){

            $pk = false;
            $local_path = $v;

            $link = md5(rand() . date("H:i:s"));
            $link = md5($link . $unit . rand());
            $link = substr($link,0,8);
            $link = $link . ".jpg";





            $this->model->imgCropAndResize($local_path,PUBLIC_PATH . "/tmp/$link",900,600);
            $this->model->imgCropAndResize($local_path,PUBLIC_PATH . "/tmp/sm_" . $link,300,200);

            $this->model->openFtpConnection();

            $this->model->putRemoteFile($link, PUBLIC_PATH . "/tmp", null, $unit, true);
            $this->model->putRemoteFile("sm_$link", PUBLIC_PATH . "/tmp", null, $unit, true);


            @unlink($local_path);
            @unlink(PUBLIC_PATH . "/tmp/$link");
            @unlink(PUBLIC_PATH . "/tmp/sm_" . $link);

            $this->model->closeFtpConnection();


            # Записать в базу
            $data = array('vmodul_id' =>  $this->registry->virtual_modul_id,
                'date_added' => date("Y-m-d H:i:s"),
                'title' => '',
                'text' => '',
                'link' => $link,
                'sort' => 100,
            );

            $PhotoModel = new PhotoModel();
            $pk = $PhotoModel->Set($data);

        }


        return $result;

    }

    function actionPlitkaMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }

    function actionRoomMultisave(){

        $this->setNoRender();

        $mess = '';
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $multisave_arr = array();

        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $this->imageToFtp($multisave_arr, $unit);

        unset($_SESSION['multisave_arr']);

        echo json_encode(array('status'=>'ok','mess'=>$mess));
    }

    function actionДобавитьФотоMultisave(){

        $this->setNoRender();

        $mess = '';
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $multisave_arr = array();

        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $this->imageToFtp($multisave_arr, $unit);

        unset($_SESSION['multisave_arr']);

        echo json_encode(array('status'=>'ok','mess'=>$mess));
    }

    function actionSvarkaMultisave(){

        $this->setNoRender();

        $mess = '';
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $multisave_arr = array();

        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $this->imageToFtp($multisave_arr, $unit);

        unset($_SESSION['multisave_arr']);

        echo json_encode(array('status'=>'ok','mess'=>$mess));
    }

    function actionCivilMultisave(){

        $this->setNoRender();

        $mess = '';
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $multisave_arr = array();

        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $this->imageToFtp($multisave_arr, $unit);

        unset($_SESSION['multisave_arr']);

        echo json_encode(array('status'=>'ok','mess'=>$mess));
    }

    function actionKitchenMultisave(){

        $this->setNoRender();

        $mess = '';
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $multisave_arr = array();

        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $this->imageToFtp($multisave_arr, $unit);

        unset($_SESSION['multisave_arr']);

        echo json_encode(array('status'=>'ok','mess'=>$mess));
    }

    function actionHallMultisave(){

        $this->setNoRender();

        $mess = '';
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $multisave_arr = array();

        if(isset($_SESSION['multisave_arr'])) $multisave_arr = $_SESSION['multisave_arr'];

        $this->imageToFtp($multisave_arr, $unit);

        unset($_SESSION['multisave_arr']);

        echo json_encode(array('status'=>'ok','mess'=>$mess));
    }

    /*
     * Загружает на сервер файлы аджаксом
     */
    function actionRepairsMultiload(){
        $this->setNoRender();

        $file = $this->model->fileupload(PUBLIC_PATH.'/tmp');

        echo json_encode(array(
            'status'   => 'ok',
            'filename' => $file,
            'file'     => PUBLIC_URL . '/tmp/' . $file
        ));
    }

    function actionHallGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->_getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionRoomGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->_getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionBalkonGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->_getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionSvarkaGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->_getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionCivilGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->_getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    private function _getPhoto($unit,$grid_unit){

        $site = HTTP_FRONTEND;
        $img_path = $site . "/Image/$unit" ."/";

        $totalItemsPerSearch = 0;
        $i = 0;
        $pagesCount = 0;
        $result = array();
        $list = array();

        $items_per_page = $this->registry->request->getParameter('rows');
        if(is_null($items_per_page)) $items_per_page = 15;

        $pagenum = $this->registry->request->getParameter('page');
        if(is_null($pagenum)) $pagenum = 1;




        $column_models = $this->model->getColumnModel($this->registry->modul_index, $grid_unit);

        $photos = $this->model->repairsKindProcess();

        if(isset($photos['count'])) $totalItemsPerSearch = $photos['whole_count'];
        if(isset($photos['data']))  $list = $photos['data'];


        if($totalItemsPerSearch > 0 AND count($list) > 0)
            foreach($list as $k => $photo){

                $link = '';
                if(isset($photo['link'])) $link = $photo['link'];
                if(isset($photo['link_sm'])) $link = $photo['link_sm'];

                $cell = array();

                foreach ($column_models as $column) {
                    switch ($column ['name']) {
                        case 'date_added':
                            $cell[] = $photo['date_added'];
                            break;
                        case 'title':
                            $cell[] = $photo['title'];
                            break;
                        case 'text':
                            $cell[] = $photo['text'];
                            break;
                        case 'link':
                            //$img = "<img src='$img_path".$link."' class='smm-picto' />";
                            $img = $img_path.$link;
                            $cell[] = $img;
                            break;
                        case 'sort':
                            $cell[] = $photo['sort'];
                            break;
                        case 'actions':
                            $switched = 'switched-off';
                            $title = 'Сделать картинку видимой';

                            if(isset($photo['is_active'])){
                                if((int)$photo['is_active'] === 1){
                                    $switched = 'switched-on';
                                    $title = 'Спрятать картинку';
                                }
                            }

                            $cell[] = "<div class='actions delete' title='удалить картинку' onClick='deleteItem(\"photo\",{$photo['photo_id']},\"$grid_unit\", \"$unit\")'></div>" .
                                      "<div class='actions vis-mode $switched' title='$title' onClick='toggleVisibility(\"photo\",{$photo['photo_id']},\"$grid_unit\", \"$unit\")'></div>"  ;
                            break;
                    }
                }

                $item = array(
                    'id' => $photo['photo_id'],
                    'cell' => $cell
                );
                array_push($result, $item);
                $i++;
            }

        $pagesCount = ceil($totalItemsPerSearch / $items_per_page);

        $data = array(
            'total' => $pagesCount,
            'page' => $pagenum,
            'records' => $i,
            'rows' => $result
        );

        return $data;


    }

    /*
     * Фрмирует массив фото для Кухни
     */
    function actionKitchenGetphoto(){

        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_kitchen";

        $site = HTTP_FRONTEND;
        $img_path = $site . "/Image/$unit" ."/";

        $totalItemsPerSearch = 0;
        $i = 0;
        $pagesCount = 0;
        $result = array();
        $list = array();

        $items_per_page = $this->registry->request->getParameter('rows');
        if(is_null($items_per_page)) $items_per_page = 15;

        $pagenum = $this->registry->request->getParameter('page');
        if(is_null($pagenum)) $pagenum = 1;

        $column_models = $this->model->getColumnModel($this->registry->modul_index, $grid_unit);

        $photos = $this->model->repairsKindProcess();

        if(isset($photos['count'])) $totalItemsPerSearch = $photos['count'];
        if(isset($photos['data']))  $list = $photos['data'];

        if($totalItemsPerSearch > 0)
            foreach($list as $k => $photo){

                $link = '';
                if(isset($photo['link'])) $link = $photo['link'];
                if(isset($photo['link_sm'])) $link = $photo['link_sm'];

                $cell = array();

                foreach ($column_models as $column) {
                    switch ($column ['name']) {
                        case 'date_added':
                            $cell[] = $photo['date_added'];
                            break;
                        case 'title':
                            $cell[] = $photo['title'];
                            break;
                        case 'text':
                            $cell[] = $photo['text'];
                            break;
                        case 'link':
                            //$img = "<img src='$img_path".$link."' class='smm-picto' />";
                            $img = $img_path.$link;
                            $cell[] = $img;
                            break;
                        case 'sort':
                            $cell[] = $photo['sort'];
                            break;
                        case 'actions':
                            $switched = 'switched-off';
                            $title = 'Сделать картинку видимой';

                            if(isset($photo['is_active'])){
                                if((int)$photo['is_active'] === 1){
                                    $switched = 'switched-on';
                                    $title = 'Спрятать картинку';
                                }
                            }

                            $cell[] = "<div class='actions delete'  title='удалить' onClick='deleteItem(\"photo\",{$photo['photo_id']},\"$grid_unit\", \"$unit\")'></div>".
                                      "<div class='actions vis-mode $switched'  title='$title' onClick='toggleVisibility(\"photo\",{$photo['photo_id']},\"$grid_unit\", \"$unit\")'></div>"  ;
                            break;
                    }
                }

                $item = array(
                    'id' => $photo['photo_id'],
                    'cell' => $cell
                );
                array_push($result, $item);
                $i++;
            }

        $pagesCount = ceil($totalItemsPerSearch / $items_per_page);

        $data = array(
            'total' => $pagesCount,
            'page' => $pagenum,
            'records' => $i,
            'rows' => $result
        );

        $this->toJson($data);

    }

    function actionPlitkaGetphoto(){

        $this->setNoRender();

        $unit = "plitka";
        $grid_unit =  "photo_plitka";
        $site = "http://remontik.kh.ua";
        $img_path = $site . "/Image/$unit" ."/";

        $totalItemsPerSearch = 0;
        $i = 0;
        $pagesCount = 0;
        $result = array();
        $list = array();

        $items_per_page = $this->registry->request->getParameter('rows');
        if(is_null($items_per_page)) $items_per_page = 15;

        $pagenum = $this->registry->request->getParameter('page');
        if(is_null($pagenum)) $pagenum = 1;

        $column_models = $this->model->getColumnModel($this->registry->modul_index, $grid_unit);

        $photos = $this->model->repairsKindProcess();




        if(isset($photos['count'])) $totalItemsPerSearch = $photos['count'];
        if(isset($photos['data']))  $list = $photos['data'];


        if($totalItemsPerSearch > 0)
            foreach($list as $k => $photo){

                $cell = array();




                foreach ($column_models as $column) {
                    switch ($column ['name']) {
                        case 'date_added':
                            $cell[] = $photo['date_added'];
                            break;
                        case 'title':
                            $cell[] = $photo['title'];
                            break;
                        case 'text':
                            $cell[] = $photo['text'];
                            break;
                        case 'link':
                            //$img = "<img src='$img_path".$photo['link']."' class='smm-picto' />";
                            $img = $img_path.$photo['link'];
                            $cell[] = $img;
                            break;
                        case 'sort':
                            $cell[] = $photo['sort'];
                            break;
                        case 'actions':
                            $switched = 'switched-off';
                            $title = 'Сделать картинку видимой';

                            if(isset($photo['is_active'])){
                                if((int)$photo['is_active'] === 1){
                                    $switched = 'switched-on';
                                    $title = 'Спрятать картинку';
                                }
                            }
                            $cell[] = "<div class='actions delete' title='удалить картинку' onClick='deleteItem(\"photo\",{$photo['photo_id']},\"$grid_unit\", \"$unit\")'></div>".
                                "<div class='actions vis-mode $switched' title='$title' onClick='toggleVisibility(\"photo\",{$photo['photo_id']},\"$grid_unit\", \"$unit\")'></div>"  ;
                            break;
                    }
                }

                $item = array(
                    'id' => $photo['photo_id'],
                    'cell' => $cell
                );
                array_push($result, $item);
                $i++;
            }

        $pagesCount = ceil($totalItemsPerSearch / $items_per_page);

        $data = array(
            'total' => $pagesCount,
            'page' => $pagenum,
            'records' => $i,
            'rows' => $result
        );




        $this->toJson($data);
    }

    private function _editcell(){
        $result = true;

        $id = $this->registry->request->postParam('id') ;
        $oper = $this->registry->request->postParam('oper') ;
        $sort = $this->registry->request->postParam('sort') ;
        $text = $this->registry->request->postParam('text') ;
        $title = $this->registry->request->postParam('title') ;

        $data = array(
            "title" => $title,
            "text" => $text,
            "sort" => $sort,
        );

        $entity = 'photo';
        $model_name = ucfirst($entity) . "Model";
        $model = new $model_name('photo_id', $id);
        $data_exists = $model->getData();


        if(isset($data_exists[0])){
            $data = array_merge($data_exists[0],$data );
        }

        $data = array(0 => $data);

        $model->setData($data);

        $model->Flush();

        return $result;
    }

    private function editCellAll(){
        $this->setNoRender();

        $status = '';

        if( ($res = $this->_editcell()) === true){
            $status = 'ok';
        }

        $this->json($data = array('responsestatus' => $status));
    }

    function actionKitchenEditcell(){
        $this->editCellAll();
    }

    function actionHallEditcell(){
        $this->editCellAll();
    }

    function actionRoomEditcell(){
        $this->editCellAll();
    }

    function actionBalkonEditcell(){
        $this->editCellAll();
    }

    function actionPlitkaEditcell(){
        $this->editCellAll();
    }

    function actionSvarkaEditcell(){
        $this->editCellAll();
    }

    function actionCivilEditcell(){
        $this->editCellAll();
    }

    // -------- plitka [virtual] точка входа ----------
    function actionPlitkaBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        $path_of_script = PUBLIC_URL .'/js/jquery.fileupload.js';
        Controller::appendHeadScript($path_of_script);

        #
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        //TODO передачу опций через set() вместо _setGridParamsXML()
        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/plitka/editCell",
            'navoptions' => array('edit'),
            //'column_model' => $colModel,
            //'grid_config' => $grid_config,
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        //TEST


        $onSelectRow = "
            function (ids) {
                console.log(2)
            }
        ";
        $onSelectRow = new Zend\Json\Expr($onSelectRow);

        //$photo_grid->setGridParameter('onSelectRow', $onSelectRow);

        $photo_grid->set($options);
        // --

       // $photo_grid->_setGridParamsXML();
       // $photo_grid->_setColumnModels();

       // $photo_grid->_setUrl(PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto");

        $photo_grid->_populate();

        /*
         * Old variant
        $photo_grid = new GridWrapper( $grid_name = "photo_plitka");
        //$photo_grid = new GridWrapper();

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/plitka/getphoto",
            'editurl' => PUBLIC_URL . "/plitka/editCell",
            //'column_model' => $colModel,
            //'grid_config' => $grid_config,
        );

        $photo_grid->set($options);

        $photo_grid->populate();


        $grid->navigator = true;
        $grid->debug = true;
        $grid->setColModel( $colModel   );



        $s = $grid-> renderGrid(
            $tbl_id = "#{$grid_name}_grid",
            $pgr_id = "#{$grid_name}_pager",
            $auto_script = true,
            $summary = null,
            $params = null,
            $auto_create_tbl = false,
            $auto_create_pgr = false,
            $echo_grid = false
        );



        $this->view->grid_plitka = $photo_grid->getHtml();
        */

        $this->html = $this->view->fetch('basic.tpl');
    } // --

    // -------- svarka [virtual] точка входа ----------
    function actionSvarkaBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');
    }

    // -------- civil [virtual] точка входа ----------
    function actionCivilBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');
    }


    // -----------------------------------------------------


    function actionKitchenДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){
        }

        return false;
    }

    function actionHallДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){
        }

        return false;
    }

    function actionRoomДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){
        }

        return false;
    }

    function actionBalkonДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){
        }

        return false;
    }

    function actionSvarkaДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){
        }

        return false;
    }

    function actionCivilДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){
        }

        return false;
    }

    function actionPlitkaДобавитьфото (){

        $this->view->Set('message',$this->message);

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb("138 тест");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        } elseif (is_numeric($this->getURIarg(2))){

        }

        return false;
    }

    private function insertPhoto($unit = null){
        # Залить фото
        $pk = false;

        $filename = $_FILES['photo']['name'];
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = md5($rnd_val . $unit . rand());
        $rnd_val = substr($rnd_val,0,8);

        $link = $rnd_val . ".jpg";

        $local_path = "tmp/";
        $file_1 = $link; //$filename;
        $file_1_up = $file_1;
        $file_1 = PUBLIC_PATH . "/tmp/$file_1";;
        $file_2 = 'sm_'.$link;
        $file_2_up = $file_2;
        $file_2 = PUBLIC_PATH . "/tmp/$file_2";


        $this->model->imgCropAndResize($_FILES['photo']['tmp_name'],$file_1,900,600);
        $this->model->imgCropAndResize($_FILES['photo']['tmp_name'],$file_2,300,200);


        if($this->model->uploadImage($file_1_up, $unit)){
            $this->model->uploadImage($file_2_up, $unit);
        }

        @unlink($file_1);
        @unlink($file_2);


        # Записать в базу
        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = substr($rnd_val,0,8);

        $link = "{$this->registry->virtual_modul_id}_{$rnd_val}" . substr($file_1_up,0,-5);

        $data = array('vmodul_id' =>  $this->registry->virtual_modul_id,
            'date_added' => date("Y-m-d H:i:s"),
            'title' => '',
            'text' => '',
            'link' => $file_1_up,
            'sort' => 100,
        );

        $PhotoModel = new PhotoModel();
        $pk = $PhotoModel->Set($data);

        #
        // Если вызов не из аджакса, редиректим
        //if(!is_null($unit))
        //    header('Location:' . PUBLIC_URL . "/" . $unit);


        return $pk;


        /*
        $tmp_name = $_FILES['photo']['name']['link']; // 6.jpg
        $tmp_type = $_FILES['photo']['type']['link']; // image/jpeg
        $tmp_file = $_FILES['photo']['tmp_name']['link']; // /tmp/php5HL2GN
        $tmp_size = $_FILES['photo']['size']['link']; // 195243

        $resolution = GetImageSize($_FILES['photo']['tmp_name']['link']);
        if($resolution[0] > 3000 OR $resolution[1] > 3000){
            $this->message = 'resolution > 3000';
            fb('resolution > 3000');
            return false;
        }

        if(($file_size = $_FILES['photo']['size']['link']) > 2048000){
            $this->message = 'size > 2M';
            fb('size > 2M');
            return false;
        }

        $title = $_POST['photo']['title'];
        $text = $_POST['photo']['text'];


        $gallery_id = 1;

        $width = 600;
        $height = 400;

        // [!]
        $parent_id = 0;
        $modul_id = 7;
        $section_id = 800;
        $gallery_id = 1;

        $new_photo_id = $this->getCountPhoto( );
        $new_photo_id ++;

        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = substr($rnd_val,0,8);

        $link = "{$section_id}_{$gallery_id}_{$rnd_val}.jpg";
        $sort = 10;

        $q = "INSERT INTO `photo` SET `parent_id` = '$parent_id',
                                      `modul_id` = '$modul_id',
                                      `section_id` = '$section_id',
                                      `gallery_id` = '$gallery_id',
                                      `date_added` = NOW(),
                                      `title` = '$title',
                                      `text` = '$text',
                                      `link` = '$link',
                                      `sort` = '$sort'
                                      ";

        $q = mysql_query($q);
        if(!$q) { fb( mysql_error() ); }

        $photo_id = mysql_insert_id();

        //
        $file = SITE . "../Image/tour/$link";

        //fb($_FILES); //
        //fb($file); // /home/babagayr/public_html/blagovist.com.ua../Image/tour/photo_1_6.jpg
        //copy($tmp_file,$file);
        $this->model->imgCropAndResize($tmp_file,$file,$width);

        */
    }
















}



?>